package cn.tedu._07weibo.controller;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import cn.tedu._07weibo.base.response.JsonResult;
import cn.tedu._07weibo.base.response.StatusCode;
import cn.tedu._07weibo.mapper.UserMapper;
import cn.tedu._07weibo.pojo.dto.UserAddParam;
import cn.tedu._07weibo.pojo.dto.UserLoginParam;
import cn.tedu._07weibo.pojo.entity.User;
import cn.tedu._07weibo.pojo.vo.UserLoginVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
@Validated
@Slf4j
@RestController
@Tag(name = "01-用户管理")
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @Operation(summary = "用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult regUser(@RequestBody @Validated UserAddParam param){
        log.debug("输入数据："+param);
        int rows=userMapper.selectUsername(param);
        if (rows>0){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user=new User();
        BeanUtils.copyProperties(param,user);
        user.setId(1L);
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        return JsonResult.OK();
    }

    @PostMapping("login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam param, HttpSession session){
        log.debug("登录参数："+param);
        UserLoginVO loginVO=userMapper.selectUserByUsernameAndPassword(param);
        if (loginVO !=null){
            session.setAttribute("user",loginVO);
            return JsonResult.OK(loginVO);
        }else {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
    }
    @GetMapping("currentUser")
    @Operation(summary = "获取当前用户信息")
    @ApiOperationSupport(order = 30)
    public JsonResult getCurrentUser(HttpSession session){
        UserLoginVO loginVO=(UserLoginVO) session.getAttribute("user");

        return JsonResult.OK(loginVO);

    }

    @GetMapping("logout")
    @Operation(summary = "退出登录")
    @ApiOperationSupport(order = 40)
    public JsonResult logoutUser(Long id,HttpSession session){
        log.debug("用户id："+id);
        session.removeAttribute("user");
        return JsonResult.OK();
    }




}
